﻿using System;
using System.IO;

namespace FirstFloor.Documents.IO
{
    /// <summary>
    /// Encapsulates a single WCF request
    /// </summary>
    public class WcfPackagePartRequest
        : IPackagePartRequest
    {
        private IDocumentWcfService service;
        private string documentName;
        private Uri partUri;

        /// <summary>
        /// Initializes a new instance of the <see cref="WcfPackagePartRequest"/> class.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="documentName">Name of the document.</param>
        /// <param name="partUri">The part URI.</param>
        public WcfPackagePartRequest(IDocumentWcfService service, string documentName, Uri partUri)
        {
            this.service = service;
            this.documentName = documentName;
            this.partUri = partUri;
        }

        /// <summary>
        /// Aborts the pending request.
        /// </summary>
        public void Abort()
        {
            // not supported
        }

        /// <summary>
        /// Begins an asynchronous load of specified part.
        /// </summary>
        /// <param name="callback">The callback.</param>
        /// <param name="state">The state.</param>
        /// <returns>
        /// An <see cref="T:System.IAsyncResult"/> that references the asynchronous request for a response.
        /// </returns>
        public IAsyncResult BeginLoadPart(AsyncCallback callback, object state)
        {
            return this.service.BeginGetDocumentPart(this.documentName, this.partUri.ToString(), callback, state);
        }

        /// <summary>
        /// Ends an asynchronous load part operation. Return null if the requested part does not exist.
        /// </summary>
        /// <param name="result">The result.</param>
        /// <returns>The part content stream.</returns>
        public Stream EndLoadPart(IAsyncResult result)
        {
            var part = this.service.EndGetDocumentPart(result);
            if (part != null) {
                return new MemoryStream(part);
            }

            return null; // part not found
        }
    }
}
